import { h } from 'vue'

/**
 * el-table加:show-summary="columnOptions.some(item => item.total)" :summary-method="getSummaries"
 */
// 合计
export const getSummaries = ({ columns, data }, columnOptions) => {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h('div', null, ['本页合计'])
      return
    }

    const values = data.map((item) => Number(item[column.property]))
    if (
      columnOptions.filter((item) => item.total).some((item) => item.value == column.property) &&
      !values.every((value) => Number.isNaN(value))
    ) {
      sums[index] = `${values
        .reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        .toFixed(2)}`
    } else {
      sums[index] = ''
    }
  })

  return sums
}

// 筛选
export const getFilters = (prop, list) => {
  const data = new Set()

  list.forEach((item) => data.add(item[prop]))

  return [...data].map((item) => ({
    text: item,
    value: item
  }))
}
export const filterHandler = (value, row, column) => {
  const property = column['property']
  return row[property] === value
}
